from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from utils.views import LoginRequiredJsonMixin
from apps.orders.models import OrderInfo
from alipay import AliPay
from alipay.utils import AliPayConfig
from meiduo_mall import settings
from apps.payment.models import Payment


class ALiPayUrlView(LoginRequiredJsonMixin, View):
    def get(self, request, order_id):
        user = request.user
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user,
                                          status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '无此订单'})
        # alipay 初始化
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调 url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG,  # 默认 False
            verbose=False,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选，请求超时时间
        )
        # 如果你是 Python3 的用户，使用默认的字符串即可
        subject = "美多商城测试订单"

        # 电脑网站支付，需要跳转到：https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount + order.freight),
            subject=subject,
            return_url=settings.ALIPAY_RETURN_URL,
            notify_url="https://example.com/notify"  # 可选，不填则使用默认 notify url
        )
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'alipay_url': alipay_url})


class PaymentStatusView(View):
    def put(self, request):
        data = request.GET.dict()
        signature = data.pop("sign")

        # verification
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调 url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG,  # 默认 False
            verbose=False,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选，请求超时时间
        )
        success = alipay.verify(data, signature)  # 验证是否交易成功
        if success:
            # print("trade succeed")
            # 读取order_id
            order_id = data.get('out_trade_no')
            # 读取支付宝流水号
            trade_id = data.get('trade_no')
            # 保存数据
            Payment.objects.create(order_id=order_id, trade_id=trade_id)
            # 修改订单状态
            OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['UNSEND'])
            return JsonResponse({'code': 0, 'errmsg': 'ok', 'trade_id': trade_id})
        return JsonResponse({'code': 400, 'errmsg': '非法请求'})


